<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>【YOLOv5】初体验 | 啊粥啊周舟の部落阁</title><meta name="author" content="Zhouwy"><meta name="copyright" content="Zhouwy"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="【YOLOv5】初体验1、 Yolov5简介Yolov5官方代码中，给出的目标检测网络中一共有4个版本，分别是Yolov5s、Yolov5m、Yolov5l、Yolov5x四个模型。 Yolov5的结构和Yolov4很相似，但也有一些不同。  上图即Yolov5的网络结构图，可以看出，还是分为输入端、Backbone、Neck、Prediction四个部分。 大家可能对Yolov3比较熟悉，因此大">
<meta property="og:type" content="article">
<meta property="og:title" content="【YOLOv5】初体验">
<meta property="og:url" content="https://gitee.com/zwyywz/zwyywz.git/2021/06/15/YOLOv5%E5%88%9D%E4%BD%93%E9%AA%8C/index.html">
<meta property="og:site_name" content="啊粥啊周舟の部落阁">
<meta property="og:description" content="【YOLOv5】初体验1、 Yolov5简介Yolov5官方代码中，给出的目标检测网络中一共有4个版本，分别是Yolov5s、Yolov5m、Yolov5l、Yolov5x四个模型。 Yolov5的结构和Yolov4很相似，但也有一些不同。  上图即Yolov5的网络结构图，可以看出，还是分为输入端、Backbone、Neck、Prediction四个部分。 大家可能对Yolov3比较熟悉，因此大">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://blog-1300216920.cos.ap-nanjing.myqcloud.com/yolo.jpg">
<meta property="article:published_time" content="2021-06-15T01:25:00.000Z">
<meta property="article:modified_time" content="2023-04-16T13:04:30.018Z">
<meta property="article:author" content="Zhouwy">
<meta property="article:tag" content="环境配置">
<meta property="article:tag" content="opencv">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://blog-1300216920.cos.ap-nanjing.myqcloud.com/yolo.jpg"><link rel="shortcut icon" href="/zwyywz/img/favicon.png"><link rel="canonical" href="https://gitee.com/zwyywz/zwyywz.git/2021/06/15/YOLOv5%E5%88%9D%E4%BD%93%E9%AA%8C/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/zwyywz/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/zwyywz/',
  algolia: undefined,
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":300},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: Zhouwy","link":"链接: ","source":"来源: 啊粥啊周舟の部落阁","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: true,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '【YOLOv5】初体验',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-04-16 21:04:30'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="///at.alicdn.com/t/c/font_4018630_wl3l75i04vl.css"><meta name="generator" content="Hexo 6.3.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/zwyywz/img/avatar.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/zwyywz/archives/"><div class="headline">文章</div><div class="length-num">17</div></a><a href="/zwyywz/tags/"><div class="headline">标签</div><div class="length-num">29</div></a><a href="/zwyywz/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/zwyywz/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/zwyywz/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/zwyywz/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 分类</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/zwyywz/note/"><i class="fa-fw iconfont icon-xuexibiji"></i><span> 学习笔记</span></a></li><li><a class="site-page child" href="/zwyywz/opensource/"><i class="fa-fw iconfont icon-xiangmu"></i><span> 开源项目</span></a></li><li><a class="site-page child" href="/zwyywz/development/"><i class="fa-fw iconfont icon-peizhi-xitongpeizhi"></i><span> 环境配置</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/zwyywz/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/zwyywz/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/zwyywz/link/"><i class="fa-fw fas fa-link"></i><span> 链接</span></a></div><div class="menus_item"><a class="site-page" href="/zwyywz/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://blog-1300216920.cos.ap-nanjing.myqcloud.com/yolo.jpg')"><nav id="nav"><span id="blog-info"><a href="/zwyywz/" title="啊粥啊周舟の部落阁"><span class="site-name">啊粥啊周舟の部落阁</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/zwyywz/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/zwyywz/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/zwyywz/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 分类</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/zwyywz/note/"><i class="fa-fw iconfont icon-xuexibiji"></i><span> 学习笔记</span></a></li><li><a class="site-page child" href="/zwyywz/opensource/"><i class="fa-fw iconfont icon-xiangmu"></i><span> 开源项目</span></a></li><li><a class="site-page child" href="/zwyywz/development/"><i class="fa-fw iconfont icon-peizhi-xitongpeizhi"></i><span> 环境配置</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/zwyywz/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/zwyywz/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/zwyywz/link/"><i class="fa-fw fas fa-link"></i><span> 链接</span></a></div><div class="menus_item"><a class="site-page" href="/zwyywz/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">【YOLOv5】初体验</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-06-15T01:25:00.000Z" title="发表于 2021-06-15 09:25:00">2021-06-15</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-04-16T13:04:30.018Z" title="更新于 2023-04-16 21:04:30">2023-04-16</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/zwyywz/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="【YOLOv5】初体验"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="【YOLOv5】初体验"><a href="#【YOLOv5】初体验" class="headerlink" title="【YOLOv5】初体验"></a>【YOLOv5】初体验</h1><h2 id="1、-Yolov5简介"><a href="#1、-Yolov5简介" class="headerlink" title="1、 Yolov5简介"></a>1、 Yolov5简介</h2><p>Yolov5官方代码中，给出的目标检测网络中一共有4个版本，分别是<strong>Yolov5s、Yolov5m、Yolov5l、Yolov5x</strong>四个模型。</p>
<p>Yolov5的结构和Yolov4很相似，但也有一些不同。</p>
<p><img src="https://blog-1300216920.cos.ap-nanjing.myqcloud.com/v2-770a51ddf78b084affff948bb522b6c0_720w.jpg" alt=""></p>
<p>上图即<strong>Yolov5</strong>的网络结构图，可以看出，还是分为<strong>输入端、Backbone、Neck、Prediction</strong>四个部分。</p>
<p>大家可能对<strong>Yolov3</strong>比较熟悉，因此大白列举它和Yolov3的一些主要的不同点，并和Yolov4进行比较。</p>
<p>​    <strong>（1）输入端：</strong>Mosaic数据增强、自适应锚框计算、自适应图片缩放<br>​            <strong>（2）Backbone：</strong>Focus结构，CSP结构<br>​            <strong>（3）Neck：</strong>FPN+PAN结构<br>​            <strong>（4）Prediction：</strong>GIOU_Loss</p>
<p><img src="https://blog-1300216920.cos.ap-nanjing.myqcloud.com/image-20210618092709617.png" alt=""></p>
<p>Yolov5作者也是在COCO数据集上进行的测试，COCO数据集的小目标占比，因此最终的四种网络结构，性能上来说各有千秋。Yolov5s网络最小，速度最少，AP精度也最低。但如果检测的以大目标为主，追求速度，倒也是个不错的选择。其他的三种网络，在此基础上，不断加深加宽网络，AP精度也不断提升，但速度的消耗也在不断增加。</p>
<p><strong>总结：在目标检测领域，速度比YOLO快的，精度基本没有YOLO高。精度比YOLO高的，速度基本没有YOLO快。</strong></p>
<h2 id="2、环境依赖"><a href="#2、环境依赖" class="headerlink" title="2、环境依赖"></a>2、环境依赖</h2><p><strong>本人环境声明：</strong></p>
<p><strong>主机：</strong><code>极链AI云GPU服务器，GPU为TITAN Xp 24。配置如下。</code></p>
<p><img src="https://blog-1300216920.cos.ap-nanjing.myqcloud.com/image-20210618093419130.png" alt=""></p>
<p><strong>系统：</strong><code>ubuntu 18.04</code></p>
<p><strong>开发工具：</strong><code>vscode+ssh</code></p>
<p><strong>step1、克隆项目</strong></p>
<p>YOLOv5源码托管在github上：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">git clone https://github.com/ultralytics/yolov5.git</span><br></pre></td></tr></table></figure>
<p><strong>step2、安装必要的环境</strong></p>
<ol>
<li>下载[<a target="_blank" rel="noopener" href="https://www.anaconda.com/products/individual#linux">Anaconda</a>]，执行安装指令：<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">bash /your_dir/Anaconda3-2021.05-Linux-x86_64.sh</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>如若不更改安装路径，一直回车或者输入yes即可完成安装</p>
<p>接下来创建YOLOv5的虚拟环境，以便于隔离不同Python版本之间的影响：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">conda create --name YOLOv5 python=3.8#创建虚拟环境</span><br><span class="line">conda activate YOLOv5#激活虚拟环境</span><br></pre></td></tr></table></figure>
<p><img src="https://blog-1300216920.cos.ap-nanjing.myqcloud.com/image-20210618094815452.png" alt=""></p>
<ol>
<li><p>安装Pytorch,在官网可以找到安装指令，选择Stable(1.9.0)版本，Linux操作系统，Conda开发环境，Python开发语言，CUDA 11.1。便能得到安装指令：</p>
<p><img src="https://blog-1300216920.cos.ap-nanjing.myqcloud.com/image-20210618100100769.png" alt=""></p>
</li>
</ol>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">conda install pytorch torchvision torchaudio cudatoolkit=11.1 -c pytorch -c nvidia</span><br></pre></td></tr></table></figure>
<ol>
<li>安装其他必备环境，YOLOv5其他必备环境都写在代码包里面，有个requirements.txt文件，其中包括了一些基本的必备环境。只需执行如下指令即可安装。</li>
</ol>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip install -U -r requirements.txt</span><br></pre></td></tr></table></figure>
<h2 id="3-、设置样本数据和标签"><a href="#3-、设置样本数据和标签" class="headerlink" title="3 、设置样本数据和标签"></a>3 、设置样本数据和标签</h2><p>此次样本数据来自某电厂的仪器仪表数据，主要是识别照片中的仪器仪表位置。</p>
<p><img src="https://blog-1300216920.cos.ap-nanjing.myqcloud.com/image-20210618104902350.png" alt=""></p>
<p>  首先，通过一个简单的脚本rename.py为这些照片进行重命名:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#rename.py</span></span><br><span class="line"><span class="comment">#coding:UTF-8</span></span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line">folder_path = <span class="string">&quot;/样本数据的路径/&quot;</span></span><br><span class="line">file_list = os.listdir(folder_path)</span><br><span class="line">os.chdir(folder_path)   </span><br><span class="line">n=<span class="number">0</span></span><br><span class="line"><span class="keyword">for</span> old_name <span class="keyword">in</span> file_list:</span><br><span class="line">    new_name = <span class="string">&quot;image&quot;</span> + <span class="built_in">str</span>(n) +<span class="string">&quot;.JPG&quot;</span></span><br><span class="line">    os.rename(old_name, new_name)</span><br><span class="line">    n=n+<span class="number">1</span></span><br></pre></td></tr></table></figure>
<p>可以得到如下结果：</p>
<p><img src="https://blog-1300216920.cos.ap-nanjing.myqcloud.com/image-20210618105318363.png" alt=""></p>
<p>接下来，为样本数据设置标签（labels）。这里使用的labelImg工具。可以直接使pip安装</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip isntall labelImg#安装labelImg</span><br></pre></td></tr></table></figure>
<p><code>labelImg</code>是一款是用于制作数据集时，对数据集进行标注的工具，labelImg是深度学习最常用的标注工具之一。</p>
<p><strong>注意：labels文件夹应和images文件在同一路径下。且labels文件夹下应有一个名为classes.txt文件，里面写着分类类别。</strong></p>
<p><img src="https://blog-1300216920.cos.ap-nanjing.myqcloud.com/llll.png" alt=""></p>
<p>运行方法为在命令行工具（Windows下可以是CMD 、Powershell等），指定image路径和分类标签路径。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">label /image路径/   /label标签保存路径/classs.txt</span><br></pre></td></tr></table></figure>
<p>之后会弹出labelImg的UI页面：将数据格式设置为YOLO才能生成txt格式的标签，按W快速选择目标区域，按A/D为上一张/下一张。 </p>
<p><img src="https://blog-1300216920.cos.ap-nanjing.myqcloud.com/image-20210619142519252.png" alt=""></p>
<p>标记完所有图片后会得到如图所示的文件结构：</p>
<p><img src="https://blog-1300216920.cos.ap-nanjing.myqcloud.com/image-20210619151051478.png" alt=""></p>
<p>至此，样本数据就准备完毕。</p>
<h2 id="4、正式训练模型"><a href="#4、正式训练模型" class="headerlink" title="4、正式训练模型"></a>4、正式训练模型</h2><p>在YOLOv5项目的<code>./models</code>文件夹下选择一个需要训练的模型，这里我们选择yolov5s.yaml,最小的一个模型进行训练，参考官方README中的<a target="_blank" rel="noopener" href="https://github.com/ultralytics/yolov5#pretrained-checkpoints">table</a>,了解不同模型的大小和推断速度。如果你选定了一个模型，那么需要修改模型对应的<code>yaml</code>文件</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># parameters</span></span><br><span class="line"><span class="attr">nc:</span> <span class="number">3</span>  <span class="comment"># number of classes     &lt;------------&gt; 设置为自己数据集的类别个数</span></span><br><span class="line"><span class="attr">depth_multiple:</span> <span class="number">0.33</span>  <span class="comment"># model depth multiple</span></span><br><span class="line"><span class="attr">width_multiple:</span> <span class="number">0.50</span>  <span class="comment"># layer channel multiple</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># anchors</span></span><br><span class="line"><span class="attr">anchors:</span></span><br><span class="line">  <span class="bullet">-</span> [<span class="number">10</span>,<span class="number">13</span>, <span class="number">16</span>,<span class="number">30</span>, <span class="number">33</span>,<span class="number">23</span>]  <span class="comment"># P3/8</span></span><br><span class="line">  <span class="bullet">-</span> [<span class="number">30</span>,<span class="number">61</span>, <span class="number">62</span>,<span class="number">45</span>, <span class="number">59</span>,<span class="number">119</span>]  <span class="comment"># P4/16</span></span><br><span class="line">  <span class="bullet">-</span> [<span class="number">116</span>,<span class="number">90</span>, <span class="number">156</span>,<span class="number">198</span>, <span class="number">373</span>,<span class="number">326</span>]  <span class="comment"># P5/32</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># YOLOv5 backbone</span></span><br><span class="line"><span class="attr">backbone:</span></span><br><span class="line">  <span class="comment"># [from, number, module, args]</span></span><br><span class="line">  [[<span class="number">-1</span>, <span class="number">1</span>, <span class="string">Focus</span>, [<span class="number">64</span>, <span class="number">3</span>]],  <span class="comment"># 0-P1/2</span></span><br><span class="line">   [<span class="number">-1</span>, <span class="number">1</span>, <span class="string">Conv</span>, [<span class="number">128</span>, <span class="number">3</span>, <span class="number">2</span>]],  <span class="comment"># 1-P2/4</span></span><br><span class="line">   [<span class="number">-1</span>, <span class="number">3</span>, <span class="string">C3</span>, [<span class="number">128</span>]],</span><br><span class="line">   [<span class="number">-1</span>, <span class="number">1</span>, <span class="string">Conv</span>, [<span class="number">256</span>, <span class="number">3</span>, <span class="number">2</span>]],  <span class="comment"># 3-P3/8</span></span><br><span class="line">   [<span class="number">-1</span>, <span class="number">9</span>, <span class="string">C3</span>, [<span class="number">256</span>]],</span><br><span class="line">   [<span class="number">-1</span>, <span class="number">1</span>, <span class="string">Conv</span>, [<span class="number">512</span>, <span class="number">3</span>, <span class="number">2</span>]],  <span class="comment"># 5-P4/16</span></span><br><span class="line">   [<span class="number">-1</span>, <span class="number">9</span>, <span class="string">C3</span>, [<span class="number">512</span>]],</span><br><span class="line">   [<span class="number">-1</span>, <span class="number">1</span>, <span class="string">Conv</span>, [<span class="number">1024</span>, <span class="number">3</span>, <span class="number">2</span>]],  <span class="comment"># 7-P5/32</span></span><br><span class="line">   [<span class="number">-1</span>, <span class="number">1</span>, <span class="string">SPP</span>, [<span class="number">1024</span>, [<span class="number">5</span>, <span class="number">9</span>, <span class="number">13</span>]]],</span><br><span class="line">   [<span class="number">-1</span>, <span class="number">3</span>, <span class="string">C3</span>, [<span class="number">1024</span>, <span class="literal">False</span>]],  <span class="comment"># 9</span></span><br><span class="line">  ]</span><br><span class="line"></span><br><span class="line"><span class="comment"># YOLOv5 head</span></span><br><span class="line"><span class="attr">head:</span></span><br><span class="line">  [[<span class="number">-1</span>, <span class="number">1</span>, <span class="string">Conv</span>, [<span class="number">512</span>, <span class="number">1</span>, <span class="number">1</span>]],</span><br><span class="line">   [<span class="number">-1</span>, <span class="number">1</span>, <span class="string">nn.Upsample</span>, [<span class="string">None</span>, <span class="number">2</span>, <span class="string">&#x27;nearest&#x27;</span>]],</span><br><span class="line">   [[<span class="number">-1</span>, <span class="number">6</span>], <span class="number">1</span>, <span class="string">Concat</span>, [<span class="number">1</span>]],  <span class="comment"># cat backbone P4</span></span><br><span class="line">   [<span class="number">-1</span>, <span class="number">3</span>, <span class="string">C3</span>, [<span class="number">512</span>, <span class="literal">False</span>]],  <span class="comment"># 13</span></span><br><span class="line"></span><br><span class="line">   [<span class="number">-1</span>, <span class="number">1</span>, <span class="string">Conv</span>, [<span class="number">256</span>, <span class="number">1</span>, <span class="number">1</span>]],</span><br><span class="line">   [<span class="number">-1</span>, <span class="number">1</span>, <span class="string">nn.Upsample</span>, [<span class="string">None</span>, <span class="number">2</span>, <span class="string">&#x27;nearest&#x27;</span>]],</span><br><span class="line">   [[<span class="number">-1</span>, <span class="number">4</span>], <span class="number">1</span>, <span class="string">Concat</span>, [<span class="number">1</span>]],  <span class="comment"># cat backbone P3</span></span><br><span class="line">   [<span class="number">-1</span>, <span class="number">3</span>, <span class="string">C3</span>, [<span class="number">256</span>, <span class="literal">False</span>]],  <span class="comment"># 17 (P3/8-small)</span></span><br><span class="line"></span><br><span class="line">   [<span class="number">-1</span>, <span class="number">1</span>, <span class="string">Conv</span>, [<span class="number">256</span>, <span class="number">3</span>, <span class="number">2</span>]],</span><br><span class="line">   [[<span class="number">-1</span>, <span class="number">14</span>], <span class="number">1</span>, <span class="string">Concat</span>, [<span class="number">1</span>]],  <span class="comment"># cat head P4</span></span><br><span class="line">   [<span class="number">-1</span>, <span class="number">3</span>, <span class="string">C3</span>, [<span class="number">512</span>, <span class="literal">False</span>]],  <span class="comment"># 20 (P4/16-medium)</span></span><br><span class="line"></span><br><span class="line">   [<span class="number">-1</span>, <span class="number">1</span>, <span class="string">Conv</span>, [<span class="number">512</span>, <span class="number">3</span>, <span class="number">2</span>]],</span><br><span class="line">   [[<span class="number">-1</span>, <span class="number">10</span>], <span class="number">1</span>, <span class="string">Concat</span>, [<span class="number">1</span>]],  <span class="comment"># cat head P5</span></span><br><span class="line">   [<span class="number">-1</span>, <span class="number">3</span>, <span class="string">C3</span>, [<span class="number">1024</span>, <span class="literal">False</span>]],  <span class="comment"># 23 (P5/32-large)</span></span><br><span class="line"></span><br><span class="line">   [[<span class="number">17</span>, <span class="number">20</span>, <span class="number">23</span>], <span class="number">1</span>, <span class="string">Detect</span>, [<span class="string">nc</span>, <span class="string">anchors</span>]],  <span class="comment"># Detect(P3, P4, P5)</span></span><br><span class="line">  ]</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>参考官方的数据集格式，需要通过一个yaml文件指定数据集的来源。故而新建一个data.yaml文件放在data文件下，容如下：</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]</span></span><br><span class="line"><span class="attr">train:</span> <span class="string">/root/yolov51/mydata/images/</span>  <span class="comment"># 训练数据集</span></span><br><span class="line"><span class="attr">val:</span> <span class="string">/root/yolov51/mydata/images/</span>  <span class="comment"># 测试数据集</span></span><br><span class="line"><span class="comment"># number of classes</span></span><br><span class="line"><span class="attr">nc:</span> <span class="number">3</span></span><br><span class="line"><span class="comment"># class names</span></span><br><span class="line"><span class="attr">names:</span> [ <span class="string">&#x27;Pointer-instrument&#x27;</span>,<span class="string">&#x27;Digital-display-instrument&#x27;</span>,<span class="string">&#x27;Indicator-light&#x27;</span> ]</span><br></pre></td></tr></table></figure>
<p>做好以上准备工作后，就可以开始训练，YOLOv5的训练文件为：train.py。在阅读源码后，发现至少需要指定如下参数才能正常训练：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">Train yolov5x on score <span class="keyword">for</span> 300 epochs</span></span><br><span class="line">python train.py --img-size 640  --epochs 300 --data ./data/mydata.yaml --cfg ./models/yolov5s.yaml --weights ./yolov5s.pt</span><br></pre></td></tr></table></figure>
<ul>
<li><code>--img-size</code>：输入图片的大小</li>
<li><code>--epochs</code>：训练步长</li>
<li><code>--data</code>:数据集配置文件</li>
<li><code>--cfg</code>：模型配置文件</li>
<li><code>--weights</code>：权重配置文件</li>
</ul>
<p>开始训练后会出现如下结果，则表示训练正常：</p>
<p><img src="/Users/zwy/Desktop/image-20210619125153656.png" alt=""></p>
<p>训练之后生成的结果会通过<code>tensorboard</code>在浏览器中打开，权重文件会保存在./runs/train/expN/weights/中，里面会有best.pt和last.pt两个文件。</p>
<p>可以看到随训练生成的分析统计：</p>
<p>比如，三类仪表的个数和在图片中的位置统计如下：</p>
<p><img src="https://blog-1300216920.cos.ap-nanjing.myqcloud.com/labels.jpg" alt=""><img src="/Users/zwy/Desktop/labels_correlogram.png" alt=""></p>
<p>最后：对于验证数据集测试效果如下：</p>
<p><img src="https://blog-1300216920.cos.ap-nanjing.myqcloud.com/test_batch0_pred.jpg" alt=""></p>
<p><img src="https://blog-1300216920.cos.ap-nanjing.myqcloud.com/test_batch1_pred.jpg" alt=""></p>
<p><img src="https://blog-1300216920.cos.ap-nanjing.myqcloud.com/test_batch2_pred.jpg" alt=""></p>
<h2 id="5、检测仪表位置"><a href="#5、检测仪表位置" class="headerlink" title="5、检测仪表位置"></a>5、检测仪表位置</h2><p>YOLOv5中提供了detect.py脚本，可以检测单张图片，多张图片，以及视频。</p>
<p>单张图片测试命令：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">python detect.py --source inference/image0.jpg --weights ./runs/train/expN/weights/best.pt </span><br></pre></td></tr></table></figure>
<p>预测结构会保存在./runs/detect/中</p>
<p>这里以一段视频为例：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">python detect.py --source /YourMP4dir/test.mp4 --weights ./runs/train/expN/weights/best.pt </span><br></pre></td></tr></table></figure>
<p>结果如下：</p>
<video width="720" height="303" controls> #或者：<video width:60% height:auto controls>
<source src="https://blog-1300216920.cos.ap-nanjing.myqcloud.com/image261.MP4" type="video/mp4">
</video>

<video width="720" height="303" controls> #或者：<video width:60% height:auto controls>
<source src="https://blog-1300216920.cos.ap-nanjing.myqcloud.com/image263.MP4" type="video/mp4">
</video>


</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://gitee.com/zwyywz/zwyywz.git">Zhouwy</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://gitee.com/zwyywz/zwyywz.git/2021/06/15/YOLOv5%E5%88%9D%E4%BD%93%E9%AA%8C/">https://gitee.com/zwyywz/zwyywz.git/2021/06/15/YOLOv5%E5%88%9D%E4%BD%93%E9%AA%8C/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://gitee.com/zwyywz/zwyywz.git" target="_blank">啊粥啊周舟の部落阁</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/zwyywz/tags/%E7%8E%AF%E5%A2%83%E9%85%8D%E7%BD%AE/">环境配置</a><a class="post-meta__tags" href="/zwyywz/tags/opencv/">opencv</a></div><div class="post_share"><div class="social-share" data-image="https://blog-1300216920.cos.ap-nanjing.myqcloud.com/yolo.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/zwyywz/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" src="/zwyywz/img/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/zwyywz/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src="/zwyywz/img/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/zwyywz/2021/06/21/YOLO%E5%8E%9F%E7%90%86%E8%AF%A6%E8%A7%A3/" title="【YOLOv5】原理详解"><img class="cover" src="https://blog-1300216920.cos.ap-nanjing.myqcloud.com/yolo.jpg" onerror="onerror=null;src='/zwyywz/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">【YOLOv5】原理详解</div></div></a></div><div class="next-post pull-right"><a href="/zwyywz/2021/06/15/%E5%9F%BA%E4%BA%8E%E6%9C%BA%E5%99%A8%E8%A7%86%E8%A7%89%E7%9A%84%E4%BB%BF%E7%94%9F%E6%9C%BA%E6%A2%B0%E6%89%8B%E6%8E%8C/" title="基于机器视觉的机械手掌"><img class="cover" src="https://blog-1300216920.cos.ap-nanjing.myqcloud.com/yolo.jpg" onerror="onerror=null;src='/zwyywz/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">基于机器视觉的机械手掌</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/zwyywz/2021/03/31/opencv%E5%AE%89%E8%A3%85%E6%95%99%E7%A8%8B/" title="【树莓派】OpenCV3源码方式安装教程"><img class="cover" src="https://blog-1300216920.cos.ap-nanjing.myqcloud.com/OpenCV.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-31</div><div class="title">【树莓派】OpenCV3源码方式安装教程</div></div></a></div><div><a href="/zwyywz/2020/09/20/Mac%20M1%20Pro%20%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA/" title="Mac M1 Pro 深度学习环境搭建"><img class="cover" src="https://blog-1300216920.cos.ap-nanjing.myqcloud.com/apple-macbook-pro-m1-2020-5-20230410110609763.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-09-20</div><div class="title">Mac M1 Pro 深度学习环境搭建</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E3%80%90YOLOv5%E3%80%91%E5%88%9D%E4%BD%93%E9%AA%8C"><span class="toc-number">1.</span> <span class="toc-text">【YOLOv5】初体验</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81-Yolov5%E7%AE%80%E4%BB%8B"><span class="toc-number">1.1.</span> <span class="toc-text">1、 Yolov5简介</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81%E7%8E%AF%E5%A2%83%E4%BE%9D%E8%B5%96"><span class="toc-number">1.2.</span> <span class="toc-text">2、环境依赖</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-%E3%80%81%E8%AE%BE%E7%BD%AE%E6%A0%B7%E6%9C%AC%E6%95%B0%E6%8D%AE%E5%92%8C%E6%A0%87%E7%AD%BE"><span class="toc-number">1.3.</span> <span class="toc-text">3 、设置样本数据和标签</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4%E3%80%81%E6%AD%A3%E5%BC%8F%E8%AE%AD%E7%BB%83%E6%A8%A1%E5%9E%8B"><span class="toc-number">1.4.</span> <span class="toc-text">4、正式训练模型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5%E3%80%81%E6%A3%80%E6%B5%8B%E4%BB%AA%E8%A1%A8%E4%BD%8D%E7%BD%AE"><span class="toc-number">1.5.</span> <span class="toc-text">5、检测仪表位置</span></a></li></ol></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By Zhouwy</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/zwyywz/js/utils.js"></script><script src="/zwyywz/js/main.js"></script><script src="/zwyywz/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    chtml: {
      scale: 1.1
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        insertScript: [200, () => {
          document.querySelectorAll('mjx-container').forEach(node => {
            if (node.hasAttribute('display')) {
              btf.wrap(node, 'div', { class: 'mathjax-overflow' })
            } else {
              btf.wrap(node, 'span', { class: 'mathjax-overflow' })
            }
          });
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax/es5/tex-mml-chtml.min.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typesetPromise()
}</script></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>